package com.gin.pixiv.callback

import com.gin.pixiv.main.Pixiv
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.awt.Desktop
import java.io.File

class RawWriteFileCallback<T> : Callback<T> {
    fun onSuccess(body: T?) {
        if (body == null) {
            return
        }
        val file = File("d:/tempJson/${System.currentTimeMillis()}.json")
        file.parentFile.mkdirs()
        Pixiv.MAPPER.writeValue(file, body)
        Desktop.getDesktop().open(file);
    }

    final override fun onResponse(call: Call<T>, response: Response<T>) {
        val rawRes = response.raw()
        if (rawRes.code != 200) {
            onError(rawRes.code, rawRes.message, call, response, rawRes);
            return;
        }
        val resBody = response.body()!!
        onSuccess(resBody);
    }

    open fun onError(
        code: Int,
        message: String,
        call: Call<T>,
        response: Response<T>,
        rawRes: okhttp3.Response,
    ) {
        throw RuntimeException("Error code: ${code}; message: ${message} ")
    }

    override fun onFailure(call: Call<T>, t: Throwable) {
        t.printStackTrace()
    }
}